import { TypographyTitle } from '@/components/Typography';
import { AutoComplete, Empty, Input, Popover, Spin, Tree } from 'antd';
import {
  ChangeEvent,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
} from 'react';
import { UserManageContext } from '../hooks';
import { IUserLeftTreeView } from '../type';
import {
  SearchOutlined,
  ReloadOutlined,
  EyeInvisibleOutlined,
  EyeOutlined,
} from '@ant-design/icons';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import pageStyles from '@/common/pageLayout.less';
import MyIcon from '@/components/MyIcon';
import cls from 'classnames';
import { loopArrayChildren } from '@/utils';
import '../styles.less';

export const UserLeftTreeView: React.FC<IUserLeftTreeView> = ({
  leftCheckReloadRight,
}) => {
  const {
    userFixCls,
    leftTreeData,
    searchValueTree,
    selectTreeKeys,
    reloadLeftTree,
    expandedTreeKeys,
    userTreeLoading,
    userManDispatch,
    autoExpandParent,
    reloadRightTable,
    rightTablePagination,
  } = useContext(UserManageContext); //拿到上下文数据

  // 左侧树 数据 变化调用
  useEffect(() => {
    if (leftTreeData && leftTreeData?.length > 0) {
      defaultCheckTree([leftTreeData[0]?.id], leftTreeData); //初始化默认选中第一个 树节点
    }
  }, [leftTreeData]);

  /**
   * 显示新增编辑按钮
   * @param id
   * @param flag
   * @returns
   */
  const onTreeNodeMouseEnter = (id: string, flag: boolean) => {
    const ele = document.getElementById(id);
    if (flag) {
      return;
    } else if (ele) {
      ele.style.display = 'block';
    }
  };

  /**
   * 隐藏新增编辑按钮
   * @param id
   * @param flag
   * @returns
   */
  const onTreeNodeMouseLeave = (id: string, flag: boolean) => {
    const ele = document.getElementById(id);
    if (flag) {
      return;
    } else if (ele) {
      ele.style.display = 'none';
    }
  };

  /**
   * 是否显示 详情气泡
   */
  const [showPopoverID, setShowPopoverID] = useState<string>('');

  /**
   * 显示 隐藏 详情方法
   * @param openID  显示图标
   * @param closeID  闭合图标
   * @param showPopo  显示详情的 id
   * @param isOpen  true 显示     false 隐藏
   */
  const clickEyeDetail = (
    openID: string,
    closeID: string,
    showPopo: string,
    isOpen: boolean,
  ) => {
    const eleOpen = document.getElementById(openID);
    const eleClose = document.getElementById(closeID);
    if (eleOpen) {
      eleOpen.style.display = isOpen ? 'none' : 'inline-block';
    }
    if (eleClose) {
      eleClose.style.display = isOpen ? 'inline-block' : 'none';
    }
    setShowPopoverID(showPopo);
  };

  // 获取选中节点
  const defaultCheckTree = (value: any, checkList: any[]) => {
    userManDispatch({
      //保存树选中的key
      type: 'user-selectTreeKeys',
      payload: value,
    });
    let posTypeIDS = handleGetId(checkList); //左侧树点击后的参数
    let rightParams = {
      ...posTypeIDS,
      ...rightTablePagination,
    };

    userManDispatch({
      //保存 点击树 需要获取的用户 参数类型
      type: 'user-leftTreeType',
      payload: posTypeIDS,
    });

    userManDispatch({
      type: 'user-searchFormValues',
      payload: {},
    });

    userManDispatch({
      //恢复分页器参数为默认
      type: 'user-rightTablePagination',
      payload: { ...rightTablePagination, rows: 10, page: 1 },
    });

    leftCheckReloadRight(); //清空右侧搜索表单的值
    reloadRightTable(rightParams); //获取用户数据
  };

  // 点击左侧树结构
  const onTreeSelect = (selectedKeys: any, selectedNodes: any) => {
    if (selectedNodes?.selected) {
      defaultCheckTree(selectedKeys, [selectedNodes?.node]);
    }
  };

  // 获取点击需要下方所有的id
  const handleGetId = (list: any[]) => {
    let paramsIDS: any = []; //参数保存
    let checkRow = list[0]; //点击选中的节点

    // 递归树
    let loop = (treeData: any[]) => {
      treeData?.forEach((item: any) => {
        if (item?.children && item?.children?.length > 0) {
          loop(item?.children);
        }
        if (checkRow?.textType == item?.textType) {
          paramsIDS?.push(item?.id);
        }
      });
    };
    loop(list);
    let idsString = paramsIDS?.join('|');
    if (checkRow?.textType == 0) {
      return { userCompanyID: idsString };
    } else if (checkRow?.textType == 1) {
      return { userDepartmentID: idsString };
    } else if (checkRow?.textType == 2) {
      return { userPositionID: idsString };
    }
  };

  // 对树结构数据处理
  const loopTreeData = (data: Record<string, any>[]): Record<string, any>[] => {
    return data?.map((item) => {
      const idName = item?.id + 'ShowBtnUserLeftTreeType';
      const detailEyeShow = item?.id + 'eyeShow' + Math.random();
      const detailEyeHiddren = item?.id + 'eyeHiddren' + Math.random();
      const showpopoverDom = item?.id + 'showpopoverDom';
      const flag = false;

      const content = (
        <div style={{ color: '#000000D9' }}>
          <p>
            状态：
            {item.open ? (
              <span style={{ color: 'green' }}>启用</span>
            ) : (
              <span style={{ color: 'red' }}>禁用</span>
            )}
          </p>
          <p>
            类型：
            {item?.textType == 0
              ? '公司'
              : item?.textType == 1
              ? '部门'
              : item?.textType == 2
              ? '岗位'
              : '--'}
          </p>
        </div>
      );
      const text = item?.text;
      const nameLength = text?.length;
      const select = text?.search(searchValueTree);
      const searchLength = searchValueTree?.length;
      const afterStr = text?.slice(0, select);
      const selectStr = searchValueTree;
      const beforeStr = text?.slice(select + searchLength, nameLength);
      const titleTree =
        select > -1 && selectStr ? (
          <span className={pageStyles['over-flow-hidden']}>
            {afterStr}
            <span style={{ color: '#f50' }}>{selectStr}</span>
            {beforeStr}
          </span>
        ) : (
          <span className={pageStyles['over-flow-hidden']}>{item?.text}</span>
        );

      // if (item?.children) {
      return {
        ...item,
        title: (
          <Popover
            placement="bottomLeft"
            content={content}
            // trigger={'hover'}
            title={item?.text}
            color={'rgb(222 222 222)'}
            overlayClassName={cls('user-popover')}
            destroyTooltipOnHide={{ keepParent: false }}
            open={showpopoverDom == showPopoverID ? true : false}
          >
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                overflow: 'hidden',
              }}
              onMouseEnter={() => {
                onTreeNodeMouseEnter(idName, flag);
              }}
              onMouseLeave={() => {
                onTreeNodeMouseLeave(idName, flag);
                clickEyeDetail(detailEyeShow, detailEyeHiddren, '', false);
              }}
            >
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  overflow: 'hidden',
                  width: '90%',
                }}
              >
                {item?.textType == 0 && <MyIcon type={'icon-bank'} />}
                {item?.textType == 1 && <MyIcon type={'icon-cluster'} />}
                {item?.textType == 2 && (
                  <MyIcon type={'icon-icon_lingdaopishi'} />
                )}
                &nbsp;
                {titleTree}
              </div>
              <div
                id={idName}
                style={{
                  whiteSpace: 'nowrap',
                  display: flag ? 'block' : 'none',
                }}
              >
                <a
                  style={{
                    display: 'inline-block',
                    marginRight: 8,
                  }}
                  id={detailEyeShow}
                  onClick={(e) => {
                    e?.stopPropagation();
                    clickEyeDetail(
                      detailEyeShow,
                      detailEyeHiddren,
                      showpopoverDom,
                      true,
                    );
                  }}
                >
                  <EyeOutlined />
                </a>
                <a
                  id={detailEyeHiddren}
                  style={{
                    display: 'none',
                    marginRight: 8,
                  }}
                  onClick={(e) => {
                    e?.stopPropagation();
                    clickEyeDetail(detailEyeShow, detailEyeHiddren, '', false);
                  }}
                >
                  <EyeInvisibleOutlined />
                </a>
              </div>
            </div>
          </Popover>
        ),
        key: item?.id,
        children:
          item?.children?.length > 0 ? loopTreeData(item?.children) : null,
      };
      // }
      // return {
      //   ...item,
      //   title: (
      //     <Popover
      //       placement="bottomLeft"
      //       content={content}
      //       trigger={'hover'}
      //       title={item.text}
      //       color={'rgb(222 222 222)'}
      //       overlayClassName={cls('user-popover')}
      //     >
      //       <div
      //         style={{
      //           display: 'flex',
      //           alignItems: 'center',
      //           justifyContent: 'space-between',
      //         }}
      //         id={item?.id}
      //       >
      //         <div
      //           style={{
      //             display: 'flex',
      //             alignItems: 'center',
      //             overflow: 'hidden',
      //           }}
      //         >
      //           {item?.textType == 0 && <MyIcon type={'icon-bank'} />}
      //           {item?.textType == 1 && <MyIcon type={'icon-cluster'} />}
      //           {item?.textType == 2 && (
      //             <MyIcon type={'icon-icon_lingdaopishi'} />
      //           )}
      //           &nbsp;
      //           {titleTree}
      //         </div>
      //       </div>
      //     </Popover>
      //   ),
      //   key: item?.id,
      // };
    });
  };

  // 渲染的树结构数据
  const posDeptTree = useMemo(() => {
    return loopTreeData(leftTreeData);
  }, [leftTreeData, searchValueTree, selectTreeKeys, showPopoverID]);

  // 搜索下拉菜单
  const autoOption = useMemo(() => {
    let option: Record<string, any>[] = [];
    const tileTreeData = (data: Record<string, any>[]) => {
      data?.forEach((item) => {
        if (item?.children && item?.children?.length > 0) {
          tileTreeData(item?.children);
        }
        if (item?.text?.includes(searchValueTree)) {
          // const text = item?.text;
          // const nameLength = text?.length;
          // const select = text?.search(searchValueTree);
          // const searchLength = searchValueTree?.length;
          // const afterStr = text?.slice(0, select);
          // const selectStr = searchValueTree;
          // const beforeStr = text?.slice(select + searchLength, nameLength);
          option.push({
            value: item?.text,
            key: item?.id,
            // label: (
            //   <div>
            //     <span>{afterStr}</span>
            //     <span style={{ color: '#f50' }}>{selectStr}</span>
            //     <span>{beforeStr}</span>
            //   </div>
            // ) as any,
          });
        }
      });
    };
    tileTreeData(leftTreeData);
    return option;
  }, [leftTreeData, searchValueTree]);

  // 保存展开的树 key
  const onTreeExpand = useCallback(
    (expandedKeys: any[]) => {
      userManDispatch({
        type: 'user-expandedTreeKeys',
        payload: expandedKeys,
      });
      userManDispatch({
        type: 'user-autoExpandParent',
        payload: false,
      });
    },
    [expandedTreeKeys],
  );

  // 搜索框改变
  const onInputChange = (e: ChangeEvent<HTMLInputElement>) => {
    userManDispatch({
      type: 'user-searchValueTree',
      payload: e.target.value,
    });
  };

  // 点击搜索
  const onAutoSelect = (value: string, option: any) => {
    const promise = new Promise((resolve, reject) => {
      const optionId = option?.key;
      const targetNode = loopArrayChildren(leftTreeData)?.find(
        (i) => i?.id === optionId,
      );

      defaultCheckTree([option?.key], [targetNode]);

      userManDispatch({
        type: 'user-searchValueTree',
        payload: value,
      });
      // userManDispatch({
      //   type: 'user-selectTreeKeys',
      //   payload: [option?.key],
      // });

      userManDispatch({
        type: 'user-expandedTreeKeys',
        payload: [targetNode?.pID],
      });
      userManDispatch({
        type: 'user-autoExpandParent',
        payload: true,
      });

      setTimeout(() => {
        scrollToAnchor(optionId);
      }, 1000);

      resolve(optionId);
    });
    promise.then((res: any) => {
      if (res) {
        // reloadTableDataSource(res);
      }
    });
  };

  // 从搜索框点击获取

  // 滚动定位
  const scrollToAnchor = (id: string) => {
    let anchorElement = document.getElementById(id);
    if (id) {
      anchorElement?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }
  };

  // 刷新
  const onReloadTree = () => {
    const promise = new Promise((resolve, reject) => {
      userManDispatch({
        type: 'remove-all-state', // 清空state
      });

      resolve(true);
    });

    promise.then((res) => {
      if (res) {
        reloadLeftTree();
      }
    });
  };

  return (
    <div className={userFixCls + 'col-div-box'}>
      <div className={userFixCls + 'treeLeft-box'}>
        <div className={userFixCls + 'treeLeft-header'}>
          <TypographyTitle
            level={4}
            style={{
              margin: 0,
            }}
          >
            组织机构
          </TypographyTitle>
        </div>
        <div className={userFixCls + 'treeLeft-body'}>
          <div className={userFixCls + 'treeLeft-body-searchInput'}>
            <AutoComplete
              style={{
                width: '100%',
              }}
              options={autoOption}
              onSelect={onAutoSelect}
            >
              <Input
                placeholder={'请按名称搜索'}
                suffix={<SearchOutlined />}
                onChange={onInputChange}
                addonAfter={<ReloadOutlined onClick={onReloadTree} />}
              />
            </AutoComplete>
          </div>

          <div className={userFixCls + 'treeLeft-child'}>
            <ScrollBarLayout
              style={{
                padding: '0rem 1rem',
              }}
            >
              <Spin
                spinning={userTreeLoading}
                style={{
                  width: '100%',
                  marginTop: 24,
                }}
              >
                {leftTreeData && leftTreeData?.length > 0 ? (
                  <Tree
                    treeData={posDeptTree}
                    blockNode={true}
                    selectedKeys={selectTreeKeys}
                    onSelect={onTreeSelect}
                    expandedKeys={expandedTreeKeys}
                    onExpand={onTreeExpand}
                    autoExpandParent={autoExpandParent}
                  />
                ) : (
                  <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                )}
              </Spin>
            </ScrollBarLayout>
          </div>
        </div>
      </div>
    </div>
  );
};
